package o2o.web.actions.area;

//商圈管理

import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.area.RegionInfoMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.DataDaoSql;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.area.CityLatLng;
import o2o.dao.PO.area.RegionInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.area.RegionInfoVO;
import o2o.web.actions.user.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class RegionAction {

    //获取商圈列表
    @RequestMapping(method = RequestMethod.POST, value = "/region/list")
    @ResponseBody
    public String region_list(String province, String city, String county, Integer page, Integer size) {
//        if (ValidateUtil.isNull(province)) {
//            return AjaxResult.errorResult("请先选择省");
//        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("请先选择市");
        }

        List<RegionInfo> list = null;

        if (ValidateUtil.isNotNull(county)) {
            list = RegionInfoMemory.getInstance().listOfCounty(city, county);
        } else {
            list = RegionInfoMemory.getInstance().listOfCity(city);
        }
        if (null == list) {
            return AjaxResult.successResult(null, 0);
        }
//        List<RegionInfoVO> voList = new ArrayList<RegionInfoVO>();
//        for (int i = 0; i < list.size(); i++) {
//            if (null != list.get(i)) {
//                RegionInfoVO info = new RegionInfoVO();
//                try {
//                    ObjectUtils.copyPropertiesExclude(list.get(i), info, null);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    return AjaxResult.errorResult("获取失败，请稍后再试");
//                }
//                voList.add(info);
//            }
//        }
//        if (voList.size() > 0) {
//            return AjaxResult.successResult(voList.size(), voList);
//        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
        if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
            List<RegionInfoVO> voList = new ArrayList<RegionInfoVO>();
            for (int i = 0; i < pageList.list.size(); i++) {
                if (null != pageList.list.get(i)) {
                    RegionInfoVO info = new RegionInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(pageList.list.get(i), info, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return AjaxResult.errorResult("获取失败，请稍后再试");
                    }
                    voList.add(info);
                }
            }
            if (voList.size() > 0) {
                return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //新增商圈
    @RequestMapping(method = RequestMethod.POST, value = "/region/add")
    @ResponseBody
    public String region_add(String token, RegionInfo regionInfo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (ValidateUtil.isNull(regionInfo.getCity())) {
            return AjaxResult.errorResult("市不能为空");
        }

        if (User.notHasCityAuth(user.getUsername(), regionInfo.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有访问该城市数据的权限");
        }


        if (null == regionInfo) {
            return AjaxResult.errorResult("请补全信息");
        }

        if (ValidateUtil.isNull(regionInfo.getName())) {
            return AjaxResult.errorResult("请填写商圈名称");
        }

        if (ValidateUtil.isNull(regionInfo.getProvince())) {
            return AjaxResult.errorResult("请填写省份");
        }
        if (ValidateUtil.isNull(regionInfo.getCity())) {
            return AjaxResult.errorResult("请填写市");
        }


//        RegionInfo regionInfo = new RegionInfo();
//        try {
//            ObjectUtils.copyPropertiesExclude(info, regionInfo, null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("新增失败，请稍后再试");
//        }


        RegionInfo info = RegionInfoMemory.getInstance().getRegionByName(regionInfo.getCity(), regionInfo.getName());
        if (null != info) {
            return AjaxResult.errorResult("当前城市已存在该商圈，请重新输入");
        }

        //创建时间
        long time = DateUtils.getCurrTime();
        regionInfo.setCreateTime(time);
        regionInfo.setCreateUser(user.getUsername());
        regionInfo.setDelFlag(0);


        try {
            UserDaoSql.getInstance().insertObj(PojoTables.RegionInfo, regionInfo);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("新增失败，请稍后重试");
        }

        // 缓存中新增
        RegionInfoMemory.getInstance().add(time);
        // 数据同步
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.REGION_INFO_ADD).setLong01(time);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return AjaxResult.successResult();
    }


    //修改商圈
    @RequestMapping(method = RequestMethod.POST, value = "/region/modify")
    @ResponseBody
    public String region_modify(String token, RegionInfoVO info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (ValidateUtil.isNull(info.getCity())) {
            return AjaxResult.errorResult("市不能为空");
        }

        if (User.notHasCityAuth(user.getUsername(), info.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有访问该城市数据的权限");
        }


        if (null == info) {
            return AjaxResult.errorResult("请补全信息");
        }
        if (ValidateUtil.isNotID(info.getId())) {
            return AjaxResult.errorResult("请选择要修改的商圈");
        }

        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("请填写商圈名称");
        }

        if (ValidateUtil.isNotID(info.getId())) {
            return AjaxResult.errorResult("请选择要修改的商圈");
        }

        RegionInfo regionInfo = RegionInfoMemory.getInstance().get(info.getId());
        if (null == regionInfo) {
            return AjaxResult.errorResult("该商圈不存在");
        }

        RegionInfo old = RegionInfoMemory.getInstance().getRegionByName(info.getCity(), info.getName());
        if (null != old && 0 != info.getId() - old.getId()) {
            return AjaxResult.errorResult("当前城市已存在该商圈，请重新输入");
        }

        //省市区是不允许改的
        info.setProvince(regionInfo.getProvince());
        info.setCity(regionInfo.getCity());
        info.setCounty(regionInfo.getCounty());

        String geocode = Geohash.encode(info.getLat(), info.getLng());
        Long areaPoint = Geohash.getArea(info.getLat(), info.getLng());
        info.setGeocode(geocode);
        info.setAreaPoint(areaPoint);

        if (null == info.getRang()) {
            info.setRang(old.getRang());
        }

        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.RegionInfo).append(" set name = '").append(info.getName()).append("',code = '").append(info.getCode())
                .append("',manager = '").append(info.getManager()).append("',isRecommend=").append(info.getIsRecommend())
                .append(",lng=").append(info.getLat()).append(",lat=").append(info.getLat()).append(",geocode='").append(info.getGeocode())
                .append("',areaPoint=").append(info.getAreaPoint()).append(",orderNo=").append(info.getOrderNo()).append(",updateUser = '")
                .append(user.getUsername()).append("',rang = ").append(info.getRang()).append("  where delFlag = 0 and id = ").append(info.getId());
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //缓存中新增
        RegionInfoMemory.getInstance().reloadRegionOfCity(info.getCity());
        // 数据同步
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.REGION_INFO_RELOAD_BY_CITY).setStr01(info.getCity());
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return AjaxResult.successResult();
    }


    //删除商圈
    @RequestMapping(method = RequestMethod.POST, value = "/region/delete")
    @ResponseBody
    public String region_delete(String token, String name, String ids, String province, String city, String county) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }

        if (User.notHasCityAuth(user.getUsername(), city, user.getUserType())) {
            return AjaxResult.errorResult("您没有访问该城市数据的权限");
        }


        if (ValidateUtil.isNotNull(ids)) {//按id删除
            if (ValidateUtil.isNull(city)) {
                return AjaxResult.errorResult("请填写市");
            }

            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.RegionInfo).append(" set delflag = 1,updateUser='").append(user.getUsername())
                    .append("' where delFlag = 0 and id in (").append(ids).append(")");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("删除失败，请稍后重试.");
            }

            //修改缓存
            RegionInfoMemory.getInstance().reloadRegionOfCity(city);
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.REGION_INFO_RELOAD_BY_CITY).setStr01(city);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }

        } else {//按名称删除
            if (ValidateUtil.isNull(name)) {
                return AjaxResult.errorResult("请填写商圈名称");
            }

            if (ValidateUtil.isNull(province)) {
                return AjaxResult.errorResult("请填写省份");
            }


            String countySql = "";
            if (ValidateUtil.isNotNull(county)) {
                countySql = " and county = '" + county + "'";
            }

            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.RegionInfo).append(" set delflag = 1,updateUser='").append(user.getUsername())
                    .append("' where name = '").append(name).append("' and delflag = 0 and province = '").append(province)
                    .append("' and city = '").append(city).append("' ").append(countySql);

            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("删除失败，请稍后重试");
            }

            RegionInfoMemory.getInstance().reloadRegionOfCity(city);
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.REGION_INFO_RELOAD_BY_CITY).setStr01(city);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }


        return AjaxResult.successResult();
    }


    //获取城市经纬度
    @RequestMapping(method = RequestMethod.POST, value = "/city/latlng")
    @ResponseBody
    public String city_lat_lng() {

        QueryCondition query = QueryCondition.getInstance();
        query.addCondition(Expression.getInstance());//所有未删除的
        String sql = DaoUtils.getSql("chn_city_latlng", query);
        List<CityLatLng> list = null;
        try {
            list = (List<CityLatLng>) DataDaoSql.getInstance().list(CityLatLng.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return AjaxResult.successResult(list.size(), list);
    }
}
